package ch.ethz.fcl.metrobuzz.controller.gui.popup;

import java.awt.BorderLayout;
import java.awt.Canvas;

import javax.swing.JFrame;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;

import ch.ethz.fcl.metrobuzz.controller.MBController;
import ch.ethz.fcl.metrobuzz.controller.gui.swing.DirectionPanel;
import ch.ethz.fcl.metrobuzz.render.techniques.bezier.Bezier;
import ch.ethz.fcl.metrobuzz.spatialindex.object2d.Point2D;
import ch.ethz.fcl.metrobuzz.tools.MBGL;
import ch.ethz.fcl.metrobuzz.viewer.MBViewer;

public class MBPopupTest {
	static float[][] ctrlCurvePoints = { { -0.5f, 0.5f }, { 0, 0 },
			{ 0.5f, 0.5f } };

	static Point2D[] ctrlPoints;
	static MBPopupMenu pm;
	Canvas canvas;

	private MBViewer view;
	private MBController control;

	public static void main(String[] arguments) {
		new MBPopupTest().run();
	}

	public MBPopupTest() {
		init();
	}

	private void init() {
		JFrame frame = new JFrame("Canvas");

		canvas = new Canvas();
		canvas.setSize(600, 600);

		try {
			Display.setParent(canvas);
		} catch (LWJGLException e1) {
			e1.printStackTrace();
		}

		ctrlPoints = new Point2D[ctrlCurvePoints.length];
		for (int i = 0; i < ctrlCurvePoints.length; i++)
			ctrlPoints[i] = new Point2D(ctrlCurvePoints[i][0],
					ctrlCurvePoints[i][1]);

		control = new MBController(view);

		frame.add(new DirectionPanel());
		frame.add(canvas, BorderLayout.CENTER);
		frame.pack();
		frame.setSize(800, 800);
		frame.setVisible(true);

		view = new MBViewer(MBViewer.ProjectionType.Perspective);
		view.createDisplay(600, 800, 600, 800, "Popup Test");
		view.getCamera().initDistance(1.0f);
		view.getCamera().disablePan();

	}

	public void run() {
		while (!Display.isCloseRequested()) {
			control.update();

			pm = new MBPopupMenu(canvas);

			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			GL11.glPushMatrix();
			view.update();
			MBGL.enableBlend();
			if (MBViewer.newUpdate)
				render();
			GL11.glPopMatrix();

			Display.update();
		}
		Display.destroy();
		System.exit(0);
	}

	private void render() {
		pm.update();

		GL11.glDisable(GL13.GL_MULTISAMPLE);
		GL11.glColor4f(1, 0, 0, 1);
		Bezier.drawBezierCurve(ctrlPoints);

		MBViewer.newUpdate = false;
	}
}
